package com.zxb.base.autoform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxb.core.common.R;
import com.zxb.core.dao.autoform.DiyColumn;
import com.zxb.core.dao.autoform.DiyColumnDao;
import com.zxb.core.dao.autoform.DiyHeader;
import com.zxb.core.dao.autoform.DiyHeaderDao;
import com.zxb.base.autoform.vo.HeaderConfigVo;
import com.zxb.core.common.Req;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class HeaderController {
    private final DiyHeaderDao headerDao;
    private final DiyColumnDao columnDao;

    @GetMapping("/header/config/list")
    public R listHeaderConfig(Long formId) {
        String username = Req.getCurrUser().getUsername();
        List<DiyHeader> configList = headerDao.list(new QueryWrapper<DiyHeader>()
                .lambda()
                .eq(DiyHeader::getFormId, formId)
                .eq(DiyHeader::getUsername, username));

        List<DiyColumn> columnList = columnDao.list(new QueryWrapper<DiyColumn>()
                .lambda()
                .eq(DiyColumn::getFormId, formId));
        return R.success(Arrays.asList(columnList, configList));
    }

    @PostMapping("/header/config/update")
    public R updateHeaderConfig(@RequestBody HeaderConfigVo headerConfigVo) {
        Long formId = headerConfigVo.getFormId();
        String username = Req.getCurrUser().getUsername();
        //删除原来表头配置
        headerDao.remove(new QueryWrapper<DiyHeader>()
                .lambda()
                .eq(DiyHeader::getFormId, formId)
                .eq(DiyHeader::getUsername, username));
        List<DiyHeader> configList = headerConfigVo.getConfigList();
        configList.stream().forEach(t->{
            t.setUsername(username);
        });
        //批量新增表头配置
        headerDao.saveBatch(configList);
        return R.success(configList.size());
    }
}
